package com.xiaomaoguai.fcp.pre.kepler.router.handler.handlers;

import com.xiaomaoguai.fcp.pre.kepler.router.exception.RouterException;
import com.xiaomaoguai.fcp.pre.kepler.router.handler.HandlerInfo;
import com.xiaomaoguai.fcp.pre.kepler.router.handler.RouterInfo;
import com.xiaomaoguai.fcp.pre.kepler.router.handler.api.Handler;
import com.xiaomaoguai.fcp.pre.kepler.router.handler.api.HandlerContext;
import com.xiaomaoguai.fcp.pre.kepler.router.handler.enums.HandleResult;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author DH
 */
public abstract class AbstractHandler<I> implements Handler<I> {

	protected Logger log = LoggerFactory.getLogger(this.getClass());

	protected HandlerInfo handlerInfo;

	@Override
	public void beforeHandle(HandlerContext<I> hc) {

	}

	@Override
	public void genInnerParam(HandlerContext<I> hc) {

	}

	@Override
	public void exceptionCaught(RouterException cause) {
	}

	@Override
	public void handleCompleted(HandlerContext<I> hc) {
		hc.setHandlerResult(HandleResult.SUCESS);
		final RouterInfo routerInfo = hc.getRouterInfo();
		if (null != routerInfo) {
			final Integer order = routerInfo.getOrder();
			if (null != order) {
				String routerName = hc.getRouter().getRouterName();
				List<RouterInfo> routerInfos = hc.getRouter().getRouterInfos(routerName);
				if (CollectionUtils.isNotEmpty(routerInfos)) {
					log.info("{} {}/{} {}-{} completed", hc.getBuf().getId(), order, routerInfos.size(), routerName, this.getClass().getSimpleName());
				} else {
					log.info("{} Rpc invoke {} completed", hc.getBuf().getId(), this.getClass().getSimpleName());
				}
			}

		}
	}

	@Override
	public HandlerInfo getHandlerInfo() {
		return handlerInfo;
	}

	@Override
	public void setHandlerInfo(HandlerInfo handlerInfo) {
		this.handlerInfo = handlerInfo;
	}

	@Override
	public String toString() {
		return handlerInfo != null ? handlerInfo.toString() : getClass().getName();
	}

	@Override
	public boolean isB2O() {
		return Boolean.FALSE;
	}

}
